﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
using System.Runtime.InteropServices;

namespace HefaMain
{
    static class Program
    {
        public static string CommondLine = "";
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] command)
        {
            if (CheckDuplicate())
            {
                return;
            }

            if (command != null && command.Length > 0)
            {
                foreach (string k in command)
                {
                    CommondLine = CommondLine + " " + k;
                }
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            KryptonManager kryptonManager = new KryptonManager();
            kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2007Silver;
            
            localXmlFile = Application.StartupPath + "\\UpdateList.xml";

            try
            {
                updaterXmlFiles = new XmlFiles(localXmlFile, true);
                tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + Program.updaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\";
            }
            catch (Exception exp)
            {
                KryptonMessageBox.Show("找不到升级配置文件.", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Application.Run(new CheckUpgrade());
        }

        public static void StartSyncTool(string entry)
        {
            Process.Start(entry, CommondLine);
        }
        public static bool CheckDuplicate()
        {
            bool createdNew;
            Mutex mutex = new Mutex(false, "SingletonFefaWinAppMutex", out createdNew);

            //如果已运行，则在前端显示
            //createdNew == false，说明程序已运行
            if (!createdNew)
            {
                Process instance = GetExistProcess();
                if (instance != null)
                {
                    SetForegroud(instance);
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// 查看程序是否已经运行
        /// </summary>
        /// <returns></returns>
        private static Process GetExistProcess()
        {
            Process currentProcess = Process.GetCurrentProcess();
            foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
            {
                if ((process.Id != currentProcess.Id) &&
                    (Assembly.GetExecutingAssembly().Location == currentProcess.MainModule.FileName))
                {
                    return process;
                }
                else
                {
                    Process[] prs = Process.GetProcessesByName("HefaSyncTool.exe");
                    if (prs != null)
                    {
                        return prs[0];
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 使程序前端显示
        /// </summary>
        /// <param name="instance"></param>
        private static void SetForegroud(Process instance)
        {
            IntPtr mainFormHandle = instance.MainWindowHandle;
            if (mainFormHandle != IntPtr.Zero)
            {
                ShowWindowAsync(mainFormHandle, 1);
                SetForegroundWindow(mainFormHandle);
            }
        }

        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        public static string tempUpdatePath;
        public static string localXmlFile;
        public static XmlFiles updaterXmlFiles;
        
    }
}
